# This file produces figures in the text and supplementary information for
#   Goehring and Lowande's Public Responses to Unilateral Policymaking. 

# See the README for more information. 

# load required packages and data



library(kableExtra)
library(tidyverse)

load('input-data/complete-data-v3.Rda') 

dv_data <- dt %>% 
  as_tibble() %>% 
  mutate(respondent_id = row_number()) %>% 
  mutate(success = case_when(
    outcome == 'win' ~ 1,
    TRUE ~ 0
  )) %>% 
  dplyr::select(respondent_id,
         condition = condition.w1,
         success,
         topic.approve.w1.bin,
         topic.approve.w2.bin,
         pres.approve.w1.bin,
         pres.approve.w2.bin,
         trumpvote.w1,
         trumpvote.w2) %>% 
  pivot_longer(topic.approve.w1.bin:trumpvote.w2) %>% 
  mutate(wave = str_remove(str_extract(name,
                                       'w\\d{1}'),
                           'w')) %>% 
  mutate(outcome = case_when(
    str_detect(name, 'topic') ~ 'topic',
    str_detect(name, 'pres') ~ 'president',
    str_detect(name, 'trump') ~ 'trump',
  )) %>% 
  dplyr::select(-name) %>% 
  group_by(respondent_id) %>% 
  mutate(success = case_when(
    sum(is.na(value)) > 0 ~ 2,
    TRUE ~ success
  )) %>% 
  ungroup()
  

dv_data_sum <- dv_data %>% 
  group_by(wave, 
           condition,
           outcome,
           success) %>% 
  summarise(mean = mean(value,
                        na.rm = TRUE),
            sd = sd(value, 
                    na.rm = TRUE),
            n = sum(!is.na(value))) %>% 
  ungroup() %>% 
  mutate(across(mean:sd, 
                ~round(., 3))) %>% 
  mutate(outcome = case_when(
    outcome == 'president' ~ 'Approve of president',
    outcome == 'topic' ~ "Approve of president's handling of topic",
    outcome == 'trump' ~ "Intend to vote for Trump in 2020"
  )) %>% 
  filter(!(wave ==2 & success == 2))

dv_out <- dv_data_sum %>% 
  dplyr::select(wave,
         outcome,
         condition,
         success,
         mean:n) %>% 
  arrange(wave, 
          outcome, 
          condition) %>% 
  rename_with(str_to_title) %>% 
  mutate(Success = case_when(
    Success == 1 ~ 'Success',
    Success == 0 ~ "Failure",
    Success == 2 ~ "Could not recontact"
  )) %>% 
  mutate(Condition = str_to_title(Condition)) %>% 
  rename(Action = Condition,
         Status = Success) %>% 
  kbl(booktabs = TRUE, 
      longtable = TRUE,
      align = 'l',
      format = 'latex',
      caption = "\\textbf{Simple Means of Dependent Variables, by Experimental Condition and Wave} Shows, for each experimental condition and wave, the mean and standard deviation of the outcome variable. The number of respondents is also reported.",
      label = 'dv-conditions') %>% 
  collapse_rows(1:2, valign = 'top') %>% 
  kable_styling(font_size = 9)

write_lines(dv_out, 
            "figures-tables/dv-conditions.txt")     


